package com.keur.money.utils.dialog

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.adapter.MullaOnItemChildClickListener
import com.keur.money.config.KeurConfigs
import com.keur.money.databinding.DialogMullaKefuBinding
import com.keur.money.http.ApiService
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.ui.user.adapter.KeurKefuAdapter
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 10:29
 * @Annotation：联系客服Dialog
 */
class KefuDialog(context: Context?) : ProDialog(context) {
    lateinit var binding: DialogMullaKefuBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //产品名称
    private var pName = KeurConfigs.KEUR_APPNAME
    //产品Token
    private var pToken = SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_TOKEN)
    //客服联系方式列表
    private var kefuAdapter: KeurKefuAdapter? = null

    override fun getRootView(): View {
        binding = DialogMullaKefuBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initWindow() {
        val params = window?.attributes
        params?.width =  WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    override fun initView() {
        binding.textWorkTime.visibility = View.GONE
        initMullaRecyclerView()
    }

    override fun initListener() {
        setOnClickListener(R.id.imgClose)
    }

    override fun initData() {
        loadMullaKefuListAction()
    }

    override fun onViewClick(v: View?) {
        dismiss()
    }

    /**
     * 事件备注
     */
    fun setMullaKefuRemark(remark: String): KefuDialog{
        this.eventRemark = remark
        return this
    }

    /**
     * 对应的产品名称
     */
    fun setMullaKefuPName(name: String): KefuDialog{
        if (name.isNotEmpty()){
            this.pName = name
        }
        return this
    }

    /**
     * 对应的产品Token
     */
    fun setMullaKefuPToken(token: String): KefuDialog{
        if (pToken.isNotEmpty()){
            this.pToken = token
        }
        return this
    }

    /**
     * 设置监听回调
     */
    fun setMullaKefuCallback(callback: IDialogCallback): KefuDialog{
        this.callback = callback
        return this
    }

    fun setMullaCancelable(flag: Boolean): KefuDialog{
        setCancelable(flag)
        return this
    }

    fun setMullaCanceledOnTouchOutside(flag: Boolean): KefuDialog{
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initMullaRecyclerView() {
        binding.recyclerView.visibility = View.GONE
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        kefuAdapter = KeurKefuAdapter(binding.recyclerView)
        binding.recyclerView.adapter = kefuAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        kefuAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            kefuAdapter?.let {
                val item = it.getItem(position)
                if (childView.id == R.id.btnFun) {//切换item
                    when (item.optString("type")) {
                        "MOBILE" -> {//电话
                            onCallAction(item)
                        }
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadMullaKefuListAction(){
        //主产品
        if (this.pName == KeurConfigs.KEUR_APPNAME){
            val data = JSONObject(SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_COMMON))
            setMullaKefuData(data)
        } else {
            val params = JSONObject().apply {
                put("product",pName)
                put("token",pToken)
            }
            val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_APP_INFO_PATH)
            HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
                override fun onRequestSuccess(data: JSONObject) {
                    when(data.optInt("code")) {
                        0 -> {//成功
                            val obj = data.optJSONObject("obj")
                            //保存所有数据
                            if (obj != null) {
                                setMullaKefuData(obj)
                            }
                        }
                    }
                }
                override fun onRequestError(error: JSONObject) {
                }
                override fun onRequestFinish() {
                }
            })
        }
    }

    /**
     * 获取联系方式列表
     */
    private fun setMullaKefuData(data: JSONObject){
        binding.textWorkTime.visibility = View.VISIBLE
        binding.recyclerView.visibility = View.VISIBLE
        val kefuList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                kefuList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                kefuList.add(obj)
            }
        }
        kefuAdapter?.data = kefuList


        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = customize?.optJSONObject("customData")
        if (customData != null){
            if (!customData.has("workDate") || !customData.has("workTime")){
                val commonCustomData = KeurCustomConfigsHelper.getMullaCustomData()
                if (commonCustomData != null) {
                    customData.put("workDate",commonCustomData.optString("workDate"))
                    customData.put("workTime",commonCustomData.optString("workTime"))
                }
            }
            workDate = customData.optString("workDate")
            workTime = customData.optString("workTime")
        }
        val showText = String.format(MyApp.app.getString(R.string.dialog_kefu_work_time),workDate,workTime)
        val spString = SpannableString(showText)
        val startIndex = showText.indexOf(workTime)
        val endIndex = startIndex + workTime.length
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF5E2C")), startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        // 创建一个StyleSpan对象，设置样式为Typeface.BOLD，即加粗
        val boldSpan = StyleSpan(Typeface.BOLD)
        spString.setSpan(boldSpan,startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textWorkTime.text = spString
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_USER_FEEDBACK_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addKeurEventAction(KeurEventType.DIALOG.KEUR_DIALOG_KEFU_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addKeurEventAction(KeurEventType.DIALOG.KEUR_DIALOG_KEFU_DISMISS,eventRemark)
    }
}